package com.cqut.forum.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.cqut.forum.entity.Filestore;
import com.cqut.forum.entity.User;
import com.cqut.forum.entity.Userfile;
import com.cqut.forum.service.IFileStoreService;
import com.cqut.forum.service.IUserFileService;
import com.cqut.forum.service.IUserService;
import com.cqut.forum.util.ConfigProperties;
import com.cqut.forum.util.CookieHandler;
import com.cqut.forum.util.DESUtils;
import com.cqut.forum.util.DateUtil;
import com.cqut.forum.util.DefaultElements;
import com.cqut.forum.util.MD5Util;
import com.cqut.forum.util.StringUtil;
@Controller
@RequestMapping(value="/file")
public class UploadController {

	private IUserService userService;
	private IFileStoreService fileStoreService;
	private IUserFileService userFileService; 

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	public IFileStoreService getFileStoreService() {
		return fileStoreService;
	}

	public void setFileStoreService(IFileStoreService fileStoreService) {
		this.fileStoreService = fileStoreService;
	}

	public IUserFileService getUserFileService() {
		return userFileService;
	}

	public void setUserFileService(IUserFileService userFileService) {
		this.userFileService = userFileService;
	}

	/**
	* @Title: uploadPhotos
	* @Description: 上传用户头像  
	* @return void  
	* @author 刘强   
	* @date 2015-5-11 下午6:29:28
	*/ 
	@RequestMapping(value="/uploadPhotos.do" , method = RequestMethod.POST)
	public void uploadPhotos(HttpServletRequest request,HttpServletResponse response){
		int result=0; 
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
	        CommonsMultipartFile image = (CommonsMultipartFile) multipartRequest.getFile("file");
	     // 获得文件名：  
	        String realFileName = image.getOriginalFilename();  
	        
	        String uuid=UUID.randomUUID().toString();
	        // 获取路径  
	        String ctxPath = null;
//			ctxPath=this.getClass().getClassLoader().getResource("").getPath()+ "images/";
				ctxPath = request.getSession().getServletContext().getRealPath(  
				        "\\") + "images\\";  
	        // 创建文件  
	        File dirPath = new File(ctxPath);  
	        if (!dirPath.exists()) {  
	            dirPath.mkdir();  
	        }  
	        File uploadFile = new File(ctxPath + uuid+getSuffix(realFileName));  
	        try {
				image.transferTo(uploadFile);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			User user=null;
			String cookieName=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);	
			if(null!=cookieName){
				user=userService.getUserByEmail(DESUtils.decode(cookieName));
			}
		    if(null!=getPath(uploadFile.getAbsolutePath())&&!getPath(uploadFile.getAbsolutePath()).equals("")) {
				user.setImagePath(getPath(uploadFile.getAbsolutePath()));
			}
			userService.saveOrUpdate(user);
			
			Map<String,Object> root=new HashMap<String,Object>();
			result=1;
			root.put("result", result);
		    StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: netdiskUpload
	* @Description: TODO  
	* @return void  
	* @author 刘强   
	* @date 2015-5-14 下午2:50:23
	*/ 
	@RequestMapping(value="/netdiskUpload.do", method = RequestMethod.POST )
	public void netdiskUpload(HttpServletRequest request,HttpServletResponse response){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
        
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		String level=null;
		String parentId=null;
		try {
			level=new String(multipartRequest.getParameter("level").getBytes("ISO8859-1"), "UTF-8");
			parentId=new String(multipartRequest.getParameter("parentId").getBytes("ISO8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
     // 获得文件名：  
        String realFileName = file.getOriginalFilename();  
        
        String uuid=UUID.randomUUID().toString();
        // 获取路径  
        String ctxPath = "";  
        if(getFileType(realFileName)==0){//其他文件
        	ctxPath = request.getSession().getServletContext().getRealPath(  
                    "/")  
                    + "\\" + "file\\other\\";
        }else if(getFileType(realFileName)==1){//文档类型
        	ctxPath = request.getSession().getServletContext().getRealPath(  
                    "/")  
                    + "\\" + "file\\document\\";
        }else if(getFileType(realFileName)==2){//音频文件
        	ctxPath = request.getSession().getServletContext().getRealPath(  
                    "/")  
                    + "\\" + "file\\music\\";
        }else if(getFileType(realFileName)==3){//视频文件
        	ctxPath = request.getSession().getServletContext().getRealPath(  
                    "/")  
                    + "\\" + "file\\vidoe\\";
        }else if(getFileType(realFileName)==4){//图片文件
        	ctxPath = request.getSession().getServletContext().getRealPath(  
                    "/")  
                    + "\\" + "file\\img\\";
        }
        // 创建文件  
        File dirPath = new File(ctxPath);  
        if (!dirPath.exists()) {  
            dirPath.mkdir();  
        }  
        File uploadFile = new File(ctxPath + uuid+getSuffix(realFileName));	
        try {
			file.transferTo(uploadFile);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        User user=null;
        String cookieName=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);	
        if(null!=cookieName){
        	user=userService.getUserByEmail(DESUtils.decode(cookieName));
        }
        String md5=MD5Util.getFileMD5(uploadFile);
        Filestore filest=fileStoreService.getFilestoreByMD5(md5);
        if(null==filest){//如果不存在md5的文件，则添加
        	Filestore filestore=new Filestore();
        	filestore.setFilemd5(MD5Util.getFileMD5(uploadFile));
        	filestore.setFileName(realFileName);
        	filestore.setFilepath(getPath(uploadFile.getAbsolutePath()));
			if(null!=user){
				filestore.setUserId(user.getId());
			}
        	filestore.setUploadDate(DateUtil.getCurrentTimestamp());
        	filestore.setFiletype(getFileType(realFileName));
        	filestore.setFilesize(getSize(uploadFile));
        	filestore.setIsfreeze(DefaultElements.ZERO);
        	fileStoreService.save(filestore);
        	filest=filestore;
        }else{
        	uploadFile.delete();
        }
        Userfile userfile=new Userfile();
        userfile.setMd5(filest.getFilemd5());
		if(null!=user){
			String rename=reName(user.getId(),realFileName);
			if(StringUtil.isEmpty(rename)){
				userfile.setFileName(rename);
			}
		}
        userfile.setUserId(user.getId());
        userfile.setIsFile(1);
        userfile.setLevel(Integer.parseInt(level));
        userfile.setParentId(Long.parseLong(parentId));
        userfile.setCreateDate(DateUtil.getCurrentTimestamp());
        userFileService.save(userfile);
	}
	/**
	* @Title: getSuffix
	* @Description: 前缀  
	* @return String  
	* @author 刘强   
	* @date 2015-5-14 下午1:45:30
	*/ 
	private String getSuffix(String str){
		String suffixstr=str.substring(str.lastIndexOf("."));
		return suffixstr;
	}
	/**
	* @Title: getFileType
	* @Description: 返回文件类型  1为文档类型 2为音频文件 3为视频文件 4为图片文件 0 为其他类型  
	* @return int  
	* @author 刘强   
	* @date 2015-5-14 下午12:26:56
	*/ 
	private int getFileType(String fileName){
		String imageType=ConfigProperties.get("netdiskImageType");
		String[] imageTypes=imageType.split("/");
		for(int i=0;i<imageTypes.length;i++){
			if(getSuffix(fileName).equals(imageTypes[i])){
				return 4;
			}
		}
		String videoType=ConfigProperties.get("netdiskVideoType");
		String[] videoTypes=videoType.split("/");
		for(int i=0;i<videoTypes.length;i++){
			if(getSuffix(fileName).equals(videoTypes[i])){
				return 3;
			}
		}
		String musicType=ConfigProperties.get("netdiskMusicType");
		String[] musicTypes=musicType.split("/");
		for(int i=0;i<musicTypes.length;i++){
			if(getSuffix(fileName).equals(musicTypes[i])){
				return 2;
			}
		}
		String documentType=ConfigProperties.get("netdiskDocumentType");
		String[] documentTypes=documentType.split("/");
		for(int i=0;i<documentTypes.length;i++){
			if(getSuffix(fileName).equals(documentTypes[i])){
				return 1;
			}
		}
		return 0;
	}
	/**
	* @Title: getPath
	* @Description: 获取相对路径 
	* @return String  
	* @author 刘强   
	* @date 2015-5-14 下午1:45:46
	*/ 
	private String getPath(String realPath){
		String projectName=ConfigProperties.get("projectName");
		String path=realPath.substring(realPath.indexOf(projectName)+projectName.length()+1);
		path=path.replace("\\", "/");
		return path;
	}
	/**
	* @Title: getSize
	* @Description: TODO  
	* @return String  
	* @author 刘强   
	* @date 2015-5-14 下午2:47:13
	*/ 
	private String getSize(File file){
		long size=file.length();
		if(size<1024){
			return size+"B";
		}else if(size<1024*1024){
			return size/1024+"KB";
		}else if(size<1024*1024*1024){
			return size/1024/1024+"M";
		}else{
			return size/1024/1024/1024+"G";
		}
	}
	/**
	* @Title: reName
	* @Description: TODO  
	* @return String  
	* @author 刘强   
	* @date 2015-5-15 下午12:51:31
	*/ 
	private String reName(Long UserId,String fileName){
		 Userfile userfile=userFileService.getUserfileByUserIdAndFileName(UserId,fileName);
		 if(null==userfile){
			 return fileName;
		 }else{
			 StringBuilder name=new StringBuilder(fileName.substring(0, fileName.lastIndexOf(".")));
			 name.append(DefaultElements.FUBEN).append(getSuffix(fileName));
			 return reName(UserId,name.toString());
		 }
	}
	
}
